package com.example.jwt.config;
import cn.hutool.core.exceptions.ExceptionUtil;
import com.example.jwt.annotation.LoginUser;
import com.example.jwt.entity.TokenUser;
import com.example.jwt.service.JwtRoleService;
import com.example.jwt.utils.MyJwtUtil;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.annotation.Resource;
import java.util.Set;

/**
 * 注解的方法参数，注入当前登录用户
 * @author mtl
 */
@Component
public class LoginUserHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver  {

    @Resource
    JwtRoleService jwtRoleService;

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        //判断对象类型是否一致 是不是 User 类型
        return parameter.getParameterType().isAssignableFrom(TokenUser.class) && parameter.hasParameterAnnotation(LoginUser.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer container,
                                  NativeWebRequest request, WebDataBinderFactory factory) throws Exception {
        //获取用户ID
        String token = request.getHeader("token");
        if(token == null){
            //没有token 直接报错
           throw ExceptionUtil.wrapRuntime("请登录");
        }
        //获取用户信息 返回用户信息
        String username = MyJwtUtil.getUsername(token);
        TokenUser tokenUser = jwtRoleService.getUserInfoByName("张三");
        Set<String> rol = jwtRoleService.findUserPermission(username);
        tokenUser.setRoles(rol);
        tokenUser.setToken(token);
        return tokenUser;
    }
}
